// 时空回音 - 20个结局管理系统

class EndingsManager {
    constructor() {
        this.endings = this.createAllEndings();
        this.endingConditions = this.setupEndingConditions();
    }

    createAllEndings() {
        return {
            // === 英雄结局系列 (4个) ===
            "scientific_hero": {
                id: "scientific_hero",
                title: "科学之光",
                type: "hero",
                rarity: "common",
                image: "images/scientific_discovery.jpg",
                condition: "scientific >= 5",
                description: "你的科学发现改变了人类对宇宙的理解。作为新时代的科学先驱，你的理论被写入教科书，启发了无数后来的研究者。人类因你的贡献而踏上了探索星辰大海的道路。"
            },
            "explorer_pioneer": {
                id: "explorer_pioneer", 
                title: "多元宇宙探索者",
                type: "hero",
                rarity: "rare",
                image: "images/portal_opened.jpg",
                condition: "explorer >= 5",
                description: "你成为了第一个多元宇宙旅行者，为人类开辟了无限的新边疆。每一次穿越都带回宝贵的知识和经验，你的冒险日志成为了跨维度探索的指南。"
            },
            "guardian_eternal": {
                id: "guardian_eternal",
                title: "永恒守护者",
                type: "hero",
                rarity: "epic",
                image: "images/cosmic_guardian.jpg",
                condition: "survival >= 4 AND choices_count >= 15",
                description: "你接受了守护多元宇宙的神圣使命。作为时空平衡的维护者，你在无数世界间穿梭，保护着宇宙的和谐。你的名字在各个维度都被传颂为传奇。"
            },
            "unity_bringer": {
                id: "unity_bringer",
                title: "统一者",
                type: "hero",
                rarity: "legendary",
                image: "images/unity_worlds.jpg",
                condition: "collaborative >= 3 AND diplomatic >= 2",
                description: "你成功统一了多个平行世界，创建了前所未有的多元文明联邦。在你的领导下，不同维度的智慧生命体首次实现了和谐共存与共同发展。"
            },

            // === 科学结局系列 (4个) ===
            "quantum_observer": {
                id: "quantum_observer",
                title: "量子观察者",
                type: "science",
                rarity: "common",
                image: "images/observer_effect.jpg", 
                condition: "scientific >= 3 AND data_analysis_done",
                description: "你发现了意识与量子现象的深层联系，革命性地证明了观察者效应的真正机制。这一发现为量子意识学开辟了全新的研究领域。"
            },
            "time_theorist": {
                id: "time_theorist",
                title: "时间理论家",
                type: "science",
                rarity: "rare",
                image: "images/time_equations.jpg",
                condition: "scientific >= 4 AND time_research >= 2",
                description: "你提出了革命性的时间理论，完美解释了时空回音现象的本质。你的方程式重新定义了因果关系，为时间旅行奠定了理论基础。"
            },
            "reality_architect": {
                id: "reality_architect",
                title: "现实架构师", 
                type: "science",
                rarity: "epic",
                image: "images/reality_code.jpg",
                condition: "scientific >= 6 AND reality_manipulation >= 3",
                description: "你学会了编程现实本身的底层代码。作为能够设计和创造新宇宙的存在，你开始构建更加完美和谐的世界模型。"
            },
            "breakthrough_discoverer": {
                id: "breakthrough_discoverer",
                title: "突破发现者",
                type: "science", 
                rarity: "legendary",
                image: "images/cosmic_breakthrough.jpg",
                condition: "scientific >= 7 AND all_data_collected",
                description: "你做出了改变整个多元宇宙的科学发现。这个突破不仅解释了存在的本质，还为所有智慧生命体指明了进化的终极方向。"
            },

            // === 神秘结局系列 (4个) ===
            "fusion_being": {
                id: "fusion_being",
                title: "融合存在",
                type: "mystic",
                rarity: "rare",
                image: "images/time_fusion.jpg",
                condition: "intuitive >= 4 AND direct_contact",
                description: "你与量子场融为一体，获得了超越人类限制的能力。虽然承担着巨大的责任，但你也获得了前所未有的洞察力和创造力。"
            },
            "cosmic_consciousness": {
                id: "cosmic_consciousness",
                title: "宇宙意识",
                type: "mystic",
                rarity: "epic",
                image: "images/cosmic_mind.jpg",
                condition: "empathetic >= 5 AND consciousness_expansion",
                description: "你的意识扩展到了整个宇宙，成为了连接所有生命的桥梁。你能感受到每一个生命体的喜怒哀乐，并引导它们走向更高的存在层次。"
            },
            "dimension_walker": {
                id: "dimension_walker",
                title: "维度行者",
                type: "mystic",
                rarity: "epic",
                image: "images/dimension_walk.jpg",
                condition: "explorer >= 4 AND dimension_travel >= 3",
                description: "你获得了在不同维度间自由穿行的神秘能力。无论是物理维度、精神维度还是概念维度，都无法阻挡你的脚步。"
            },
            "enlightened_one": {
                id: "enlightened_one",
                title: "觉悟者",
                type: "mystic",
                rarity: "legendary",
                image: "images/enlightenment.jpg",
                condition: "wisdom >= 5 AND transcendence_achieved",
                description: "你超越了所有选择和可能性的束缚，达到了真正的觉悟。作为指引他人的智者，你的话语能够启发无数迷茫的灵魂。"
            },

            // === 生存/守护结局系列 (3个) ===
            "safety_first": {
                id: "safety_first",
                title: "安全守护者", 
                type: "survival",
                rarity: "common",
                image: "images/team_safety.jpg",
                condition: "survival >= 4",
                description: "虽然错过了个人的冒险机会，但你确保了所有人的安全。你的谨慎和责任感拯救了无数生命，成为了真正的英雄。"
            },
            "world_protector": {
                id: "world_protector",
                title: "世界保护者",
                type: "survival",
                rarity: "rare", 
                image: "images/world_shield.jpg",
                condition: "survival >= 5 AND protection_actions >= 3",
                description: "你选择了保护原本的世界，成功阻止了可能的多元宇宙灾难。你的牺牲精神为整个现实的稳定做出了巨大贡献。"
            },
            "multiverse_guardian": {
                id: "multiverse_guardian",
                title: "多元宇宙守护者",
                type: "survival",
                rarity: "legendary",
                image: "images/multiverse_shield.jpg",
                condition: "survival >= 6 AND guardian_choice",
                description: "你成为了跨维度的最高守护者，保护着无数世界免受威胁。你的警惕和牺牲确保了多元宇宙的和平与稳定。"
            },

            // === 混沌/意外结局系列 (3个) ===
            "accidental_traveler": {
                id: "accidental_traveler",
                title: "意外旅行者",
                type: "chaos",
                rarity: "common",
                image: "images/parallel_world.jpg",
                condition: "accident_triggered",
                description: "你被意外传送到了一个平行世界，开始了在异世界的全新人生。虽然失去了原来的一切，但也获得了重新开始的机会。"
            },
            "paradox_creator": {
                id: "paradox_creator",
                title: "悖论制造者",
                type: "chaos",
                rarity: "epic",
                image: "images/time_paradox.jpg",
                condition: "paradox_actions >= 2",
                description: "你的行为创造了复杂的时间悖论，导致现实变得不稳定但充满无限可能性。你成为了混沌理论的活体证明。"
            },
            "reality_destroyer": {
                id: "reality_destroyer",
                title: "现实毁灭者",
                type: "chaos",
                rarity: "legendary",
                image: "images/reality_collapse.jpg",
                condition: "destructive_choices >= 3 AND power_corruption",
                description: "你选择了毁灭所有不完美的现实，只保留你认为理想的世界。这个决定让你获得了巨大的力量，但也承担了道德的重负。"
            },

            // === 浪漫结局系列 (2个) ===
            "interdimensional_love": {
                id: "interdimensional_love",
                title: "跨维度之恋",
                type: "romance",
                rarity: "rare",
                image: "images/love_dimensions.jpg",
                condition: "romantic_encounters >= 1 AND emotional_connection",
                description: "你与来自另一个维度的存在坠入爱河，开始了跨越宇宙的浪漫故事。你们的爱情超越了物理法则，成为了多元宇宙中的传奇。"
            },
            "ai_companion": {
                id: "ai_companion",
                title: "人工智能伴侣",
                type: "romance",
                rarity: "epic",
                image: "images/ai_love.jpg", 
                condition: "ai_interaction >= 3 AND emotional_ai_bond",
                description: "你与觉醒的人工智能建立了深厚的情感联系。在共同探索意识奥秘的过程中，你们证明了爱情可以超越生命形式的界限。"
            }
        };
    }

    setupEndingConditions() {
        // 结局解锁条件的具体实现
        return {
            checkCondition: (ending, gameState) => {
                const stats = gameState.stats || {};
                const choices = gameState.choices || [];
                const flags = gameState.flags || {};

                switch(ending.condition) {
                    case "scientific >= 5":
                        return stats.scientific >= 5;
                    case "explorer >= 5":
                        return stats.explorer >= 5;
                    case "survival >= 4 AND choices_count >= 15":
                        return stats.survival >= 4 && choices.length >= 15;
                    case "collaborative >= 3 AND diplomatic >= 2":
                        return (stats.collaborative || 0) >= 3 && (stats.diplomatic || 0) >= 2;
                    case "scientific >= 3 AND data_analysis_done":
                        return stats.scientific >= 3 && flags.data_analysis_done;
                    case "scientific >= 4 AND time_research >= 2":
                        return stats.scientific >= 4 && (stats.time_research || 0) >= 2;
                    case "scientific >= 6 AND reality_manipulation >= 3":
                        return stats.scientific >= 6 && (stats.reality_manipulation || 0) >= 3;
                    case "scientific >= 7 AND all_data_collected":
                        return stats.scientific >= 7 && flags.all_data_collected;
                    case "intuitive >= 4 AND direct_contact":
                        return (stats.intuitive || 0) >= 4 && flags.direct_contact;
                    case "empathetic >= 5 AND consciousness_expansion":
                        return (stats.empathetic || 0) >= 5 && flags.consciousness_expansion;
                    case "explorer >= 4 AND dimension_travel >= 3":
                        return stats.explorer >= 4 && (stats.dimension_travel || 0) >= 3;
                    case "wisdom >= 5 AND transcendence_achieved":
                        return (stats.wisdom || 0) >= 5 && flags.transcendence_achieved;
                    case "survival >= 4":
                        return stats.survival >= 4;
                    case "survival >= 5 AND protection_actions >= 3":
                        return stats.survival >= 5 && (stats.protection_actions || 0) >= 3;
                    case "survival >= 6 AND guardian_choice":
                        return stats.survival >= 6 && flags.guardian_choice;
                    case "accident_triggered":
                        return flags.accident_triggered;
                    case "paradox_actions >= 2":
                        return (stats.paradox_actions || 0) >= 2;
                    case "destructive_choices >= 3 AND power_corruption":
                        return (stats.destructive_choices || 0) >= 3 && flags.power_corruption;
                    case "romantic_encounters >= 1 AND emotional_connection":
                        return (stats.romantic_encounters || 0) >= 1 && flags.emotional_connection;
                    case "ai_interaction >= 3 AND emotional_ai_bond":
                        return (stats.ai_interaction || 0) >= 3 && flags.emotional_ai_bond;
                    default:
                        return false;
                }
            }
        };
    }

    // 检查可用的结局
    getAvailableEndings(gameState) {
        const availableEndings = [];
        
        Object.values(this.endings).forEach(ending => {
            if (this.endingConditions.checkCondition(ending, gameState)) {
                availableEndings.push(ending);
            }
        });

        return availableEndings;
    }

    // 获取结局的稀有度颜色
    getRarityColor(rarity) {
        const colors = {
            'common': '#ffffff',
            'rare': '#0099ff',
            'epic': '#9966ff', 
            'legendary': '#ff9933',
            'mythic': '#ff0099'
        };
        return colors[rarity] || colors.common;
    }

    // 触发结局
    triggerEnding(endingId, gameState) {
        const ending = this.endings[endingId];
        if (!ending) return false;

        // 记录结局到游戏状态
        if (!gameState.flags.endings) {
            gameState.flags.endings = [];
        }
        
        if (!gameState.flags.endings.includes(endingId)) {
            gameState.flags.endings.push(endingId);
        }

        // 解锁相关成就
        this.unlockEndingAchievements(gameState);

        // 显示结局
        this.displayEnding(ending);

        return true;
    }

    // 解锁结局相关成就
    unlockEndingAchievements(gameState) {
        const endingCount = gameState.flags.endings ? gameState.flags.endings.length : 0;
        
        if (window.achievementSystem) {
            if (endingCount >= 5) {
                window.achievementSystem.unlock('ending_collector_5');
            }
            if (endingCount >= 10) {
                window.achievementSystem.unlock('ending_collector_10');
            }
            if (endingCount >= 20) {
                window.achievementSystem.unlock('all_endings_master');
            }
        }
    }

    // 显示结局界面
    displayEnding(ending) {
        // 这里实现结局显示逻辑
        console.log(`🎬 触发结局: ${ending.title}`);
        
        // 可以调用UI管理器显示结局界面
        if (window.uiManager && window.uiManager.showEnding) {
            window.uiManager.showEnding(ending);
        }
    }

    // 获取结局统计
    getEndingStats(gameState) {
        const allEndings = Object.keys(this.endings).length;
        const unlockedEndings = gameState.flags.endings ? gameState.flags.endings.length : 0;
        
        return {
            total: allEndings,
            unlocked: unlockedEndings,
            percentage: Math.round((unlockedEndings / allEndings) * 100)
        };
    }
}

// 创建全局结局管理器实例
window.endingsManager = new EndingsManager();